<?php
require 'db.php'; // 包含数据库连接
require 'vendor/autoload.php'; // 引入 Composer 自动加载器
include_once 'secret/jwt.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

// 获取 JWT
if (!isset($_COOKIE['token'])) {
    header('Location: index.php');
    exit();
}

$jwt = $_COOKIE['token'];

try {
    $decoded = JWT::decode($jwt, new Key($secretKey, 'HS256'));
    $user_id = $decoded->data->id;
} catch (Exception $e) {
    echo json_encode(['error' => '无效的令牌: ' . $e->getMessage()]);
    exit();
}

$article_id = $_POST['article_id'];

// 检查用户是否已经点赞过该文章
$query = $conn->prepare("SELECT * FROM article_likes WHERE article_id = ? AND user_id = ?");
$query->bind_param("ii", $article_id, $user_id);
$query->execute();
$result = $query->get_result();

if ($result->num_rows > 0) {
    // 取消点赞
    $delete = $conn->prepare("DELETE FROM article_likes WHERE article_id = ? AND user_id = ?");
    $delete->bind_param("ii", $article_id, $user_id);
    $delete->execute();
    echo json_encode(["status" => "unliked"]);
} else {
    // 点赞
    $insert = $conn->prepare("INSERT INTO article_likes (article_id, user_id) VALUES (?, ?)");
    $insert->bind_param("ii", $article_id, $user_id);
    $insert->execute();
    echo json_encode(["status" => "liked"]);
}
?>